<template>
  <view class="register-page bg-gray-100 min-h-screen p-4">
    <!-- 标题 -->
    <view class="text-center py-8">
      <view class="text-2xl font-bold text-green-600">用户注册</view>
      <view class="text-sm text-gray-500 mt-2">欢迎加入跃动西大</view>
    </view>

    <!-- 注册表单 -->
    <view class="bg-white rounded-lg shadow-md p-4">
      <!-- 手机号 -->
      <view class="mb-4">
        <view class="text-gray-700 mb-2">手机号</view>
        <input 
          type="number" 
          v-model="formData.mobile" 
          placeholder="请输入手机号" 
          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:border-green-500 outline-none"
        />
        <view v-if="errors.mobile" class="text-red-500 text-xs mt-1">{{ errors.mobile }}</view>
      </view>

      <!-- 图形验证码 -->
      <view class="mb-4">
        <view class="text-gray-700 mb-2">图形验证码</view>
        <view class="flex">
          <input 
            type="text" 
            v-model="formData.code" 
            placeholder="请输入验证码" 
            class="flex-1 border border-gray-300 rounded-lg px-3 py-2 focus:border-green-500 outline-none"
          />
          <view 
            @click="refreshCaptcha" 
            class="ml-2 border border-gray-300 rounded-lg flex items-center justify-center overflow-hidden"
            style="width: 120px; height: 44px;"
          >
            <!-- 图形验证码显示 -->
            <view class="flex items-center justify-center w-full h-full">
              <text 
                v-for="(char, index) in captchaText" 
                :key="index"
                :style="{ color: captchaColors[index], transform: `rotate(${Math.random() * 20 - 10}deg)` }"
                class="text-xl font-bold mx-1"
              >
                {{ char }}
              </text>
            </view>
          </view>
        </view>
        <view class="text-xs text-gray-500 mt-1">点击图形刷新验证码</view>
        <view v-if="errors.code" class="text-red-500 text-xs mt-1">{{ errors.code }}</view>
      </view>

      <!-- 密码 -->
      <view class="mb-4">
        <view class="text-gray-700 mb-2">密码</view>
        <input 
          type="password" 
          v-model="formData.password" 
          placeholder="请设置密码" 
          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:border-green-500 outline-none"
        />
        <view v-if="errors.password" class="text-red-500 text-xs mt-1">{{ errors.password }}</view>
      </view>

      <!-- 确认密码 -->
      <view class="mb-4">
        <view class="text-gray-700 mb-2">确认密码</view>
        <input 
          type="password" 
          v-model="formData.confirmPassword" 
          placeholder="请再次输入密码" 
          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:border-green-500 outline-none"
        />
        <view v-if="errors.confirmPassword" class="text-red-500 text-xs mt-1">{{ errors.confirmPassword }}</view>
      </view>

      <!-- 昵称 -->
      <view class="mb-4">
        <view class="text-gray-700 mb-2">昵称 (选填)</view>
        <input 
          type="text" 
          v-model="formData.nickname" 
          placeholder="请输入昵称" 
          class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:border-green-500 outline-none"
        />
      </view>

      <!-- 注册按钮 -->
      <button 
        @click="handleRegister" 
        :disabled="registering"
        class="w-full bg-green-600 text-white py-3 rounded-lg mt-4 disabled:bg-gray-400"
      >
        {{ registering ? '注册中...' : '立即注册' }}
      </button>

      <!-- 登录链接 -->
      <view class="text-center mt-4">
        <text class="text-gray-600">已有账号？</text>
        <text @click="goToLogin" class="text-green-600 ml-1">立即登录</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { register } from '@/api/auth'
import { useUserStore } from '@/store/modules/user'
import { generateSimpleCaptcha } from '@/utils/captcha'

// 用户store
const userStore = useUserStore()

// 表单数据
const formData = reactive({
  mobile: '',
  code: '',
  password: '',
  confirmPassword: '',
  nickname: ''
})

// 错误信息
const errors = reactive({
  mobile: '',
  code: '',
  password: '',
  confirmPassword: ''
})

// 状态控制
const registering = ref(false)

// 验证码相关
const captchaText = ref('')
const captchaColors = ref([])
const correctCaptcha = ref('')

// 初始化图形验证码
onMounted(() => {
  refreshCaptcha()
})

// 刷新验证码
function refreshCaptcha() {
  const captcha = generateSimpleCaptcha()
  correctCaptcha.value = captcha.text
  captchaText.value = captcha.text.split('')
  captchaColors.value = captcha.colors
  
  // 清空用户输入的验证码
  formData.code = ''
}

// 验证表单
function validateForm() {
  let isValid = true
  
  // 重置错误信息
  errors.mobile = ''
  errors.code = ''
  errors.password = ''
  errors.confirmPassword = ''
  
  // 验证手机号
  if (!formData.mobile) {
    errors.mobile = '请输入手机号'
    isValid = false
  } else if (!/^1[3-9]\d{9}$/.test(formData.mobile)) {
    errors.mobile = '手机号格式不正确'
    isValid = false
  }
  
  // 验证验证码
  if (!formData.code) {
    errors.code = '请输入验证码'
    isValid = false
  } else if (formData.code.toLowerCase() !== correctCaptcha.value.toLowerCase()) {
    errors.code = '验证码不正确'
    isValid = false
    // 验证码错误时刷新验证码
    refreshCaptcha()
  }
  
  // 验证密码
  if (!formData.password) {
    errors.password = '请设置密码'
    isValid = false
  } else if (formData.password.length < 4 || formData.password.length > 16) {
    errors.password = '密码长度为4-16位'
    isValid = false
  }
  
  // 验证确认密码
  if (!formData.confirmPassword) {
    errors.confirmPassword = '请再次输入密码'
    isValid = false
  } else if (formData.confirmPassword !== formData.password) {
    errors.confirmPassword = '两次输入的密码不一致'
    isValid = false
  }
  
  return isValid
}

// 注册处理
async function handleRegister() {
  // 表单验证
  if (!validateForm()) {
    return
  }
  
  try {
    registering.value = true
    
    // 调用注册接口 - 不需要传递验证码，因为已经在前端验证过了
    const res = await register({
      mobile: formData.mobile,
      // 不需要传递code参数，前端已经验证过图形验证码
      password: formData.password,
      nickname: formData.nickname || undefined,
      avatar: undefined // 可选头像
    })
    
    // 注册成功，存储token
    if (res.token) {
      // 更新用户信息
      userStore.updateUserInfo({
        id: res.userId,
        name: formData.nickname || '用户' + formData.mobile.substring(7),
        mobile: formData.mobile
      })
      
      // 提示注册成功
      uni.showToast({
        title: '注册成功',
        icon: 'success'
      })
      
      // 跳转到首页
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/index/index'
        })
      }, 1500)
    }
  } catch (error) {
    // 提示错误
    uni.showToast({
      title: error.message || '注册失败',
      icon: 'none'
    })
    // 刷新验证码
    refreshCaptcha()
  } finally {
    registering.value = false
  }
}

// 跳转到登录页
function goToLogin() {
  uni.navigateTo({
    url: '/pages/profile/login'
  })
}
</script>

<style>
/* 可以添加自定义样式 */
</style>
